using Cysharp.Threading.Tasks;
using DG.Tweening;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public class UIN_StoryBackground : UIBaseNode
    {
        #region Template Generate,don't modify

        protected class UIB_UIN_SpeakerItem
        {
            #region ObjectBinding Generate
            public UnityEngine.GameObject rollBg { protected set; get; }
            public IQIGame.Onigao.Framework.ExRawImage img_bg { protected set; get; }
            public IQIGame.Onigao.Framework.ExRawImage rollBG_1 { protected set; get; }
            public IQIGame.Onigao.Framework.ExRawImage rollBG_2 { protected set; get; }
            public UnityEngine.CanvasGroup uIN_StoryBackground { protected set; get; }
            public virtual void InitBinding(ObjectBinding __binding)
            {
                __binding.TryGetVariableValue<UnityEngine.GameObject>("rollBg", out var __tbv0);
                this.rollBg = __tbv0;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExRawImage>("img_bg", out var __tbv1);
                this.img_bg = __tbv1;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExRawImage>("rollBG_1", out var __tbv2);
                this.rollBG_1 = __tbv2;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExRawImage>("rollBG_2", out var __tbv3);
                this.rollBG_2 = __tbv3;
                __binding.TryGetVariableValue<UnityEngine.CanvasGroup>("uIN_StoryBackground", out var __tbv4);
                this.uIN_StoryBackground = __tbv4;
            }
            #endregion ObjectBinding Generate
        }

        #endregion Template Generate,don't modify

        #region fields

        private EStoryBackGroundType _backGroundType;
        private RenderTexture _blackGroundRT;
        private string _imagePath;

        private Tweener _rollBg;

        public bool autoDelete;

        #endregion fields

        #region properties

        protected UIB_UIN_SpeakerItem ui { get; set; }
        protected UIMsgDispatcher uiMsgDispatcher => this._msgDispatcher as UIMsgDispatcher;

        #endregion properties

        protected override void BeforeInit()
        {
            ui = new UIB_UIN_SpeakerItem();
            ui.InitBinding(this.csObjBind);
        }

        protected override void OnInit()
        {
            this.isUpdate = true;
        }

        protected override void OnShow()
        {
        }

        protected override void OnHide()
        {
            this.Reset();
        }

        /// <summary>
        /// 添加UGUI侦听
        /// </summary>
        protected override void AddUGUIListener()
        {
        }

        /// <summary>
        /// 添加全局侦听（MsgDispatcher）
        /// </summary>
        protected override void AddMsgListeners()
        {
        }

        protected override void OnDispose()
        {
            this.Reset();
        }

        #region methonds

        public bool Equals(EStoryBackGroundType backGroundType, string imagePath)
        {
            return backGroundType != EStoryBackGroundType.Delete &&
                   (backGroundType == EStoryBackGroundType.None ||
                    (backGroundType == this._backGroundType && imagePath == this._imagePath));
        }

        public async UniTask<bool> ShowBackground(EStoryBackGroundType backGroundType, string imagePath)
        {
            var rLastType = this._backGroundType;
            this._backGroundType = backGroundType;
            this._imagePath = imagePath;
            // 等一帧来让位置设置生效
            await UniTask.Yield();
            //背景
            switch (backGroundType)
            {
                case EStoryBackGroundType.Delete:
                    this.ui.img_bg.gameObject.SetActive(false);
                    return false;
                case EStoryBackGroundType.BlurGenerate:
                    if (backGroundType == rLastType)
                    {
                        break;
                    }
                    this._blackGroundRT = StoryManager.Instance.blurRT;
                    if (this._blackGroundRT != null)
                    {
                        this.ui.img_bg.texture = this._blackGroundRT;
                        this.ui.img_bg.gameObject.SetActive(true);
                    }
                    break;
                case EStoryBackGroundType.Asset:
                    this.ui.img_bg.texture = await this.LoadTexture(PathConstant.GetStoryBackground(imagePath));
                    this.ui.img_bg.gameObject.SetActive(true);
                    break;
                case EStoryBackGroundType.Roll:
                    var rSprite = await this.LoadTexture(PathConstant.GetStoryBackground(imagePath));
                    this.ui.rollBG_1.texture = rSprite;
                    this.ui.rollBG_2.texture = rSprite;
                    this.ui.rollBg.gameObject.SetActive(true);
                    this.StartBgRoll();
                    break;
                default:
                    // 保持不变
                    break;
            }
            return true;
        }

        private void StartBgRoll()
        {
            this.StopBgRoll();
            var nWidth = this.ui.rollBG_1.rectTransform.sizeDelta.x;
            var rStartPos = new Vector3(nWidth, 0, 0);
            var rEndPos = new Vector3(-nWidth, 0, 0);

            this._rollBg = DOTween.To(
                () => this.ui.rollBG_1.rectTransform.localPosition,
                (x) =>
                {
                    this.ui.rollBG_1.rectTransform.localPosition = x;
                    this.ui.rollBG_2.rectTransform.localPosition = x + rStartPos;
                },
                rEndPos, 2).SetEase(Ease.Linear).SetLoops(-1);

#if UNITY_EDITOR
            if (!Application.isPlaying)
            {
                this._rollBg.StartPreview();
            }
#endif
        }

        private void StopBgRoll()
        {
            this._rollBg?.Kill();
            this._rollBg = null;

            var nWidth = this.ui.rollBG_1.rectTransform.sizeDelta.x;
            var rStartPos = new Vector3(nWidth, 0, 0);
            this.ui.rollBG_1.rectTransform.localPosition = Vector3.zero;
            this.ui.rollBG_2.rectTransform.localPosition = rStartPos;

#if UNITY_EDITOR
            if (!Application.isPlaying)
            {
                DoTweenUtil.StopPreview();
            }
#endif
        }

        private async UniTask<Texture> LoadTexture(string path)
        {
#if UNITY_EDITOR
            if (StoryClientUtil.IsEditorMode)
            {
                return UnityEditor.AssetDatabase.LoadAssetAtPath<Texture>("Assets/" + path);
            }
            else
#endif
            {
                return await this.resLoader.LoadABAssetAwait<Texture>(path);
            }
        }

        private void Reset()
        {
            this.ui.img_bg.gameObject.SetActive(false);
            this.ui.img_bg.texture = null;
            this.ui.rollBg.gameObject.SetActive(false);
            this.ui.uIN_StoryBackground.alpha = 1;
            this.StopBgRoll();
            // this.resLoader?.ReleaseAllRes();
            this._backGroundType = EStoryBackGroundType.None;
            this.autoDelete = false;
        }

        public float GetAlpha()
        {
            return this.ui.uIN_StoryBackground.alpha;
        }

        public void SetAlpha(float alpha)
        {
            this.ui.uIN_StoryBackground.alpha = alpha;
        }
        #endregion methonds
    }
}